import React, { Component } from "react"
import InfoTable from "../common/sourceTable"
import { Card, Button, Popconfirm, message } from "antd"
import { FormInstance } from 'antd/lib/form'
import { EditFilled, DeleteFilled } from '@ant-design/icons'
import { getPowerInfo, addPowerInfo, editPowerInfo, deletePowerInfo, getPowerAll } from "@net/power/index"
import DialogForm from '../common/dialogForm'
import Modal from '@comp/Modal'
import HeaderSearch from '../common/headerSearch'
import "../../index.scss"
import Power from "@comm/power"


interface ISelectTreeData {
    value: string | number;
    label?: React.ReactNode;
    disabled?: boolean;
    children?: any;
}
interface IPorps { }
interface IStates {
    powerList: any[]
    loading: boolean,
    popVisible: string,
    visible: boolean,
    title: string,
    delId: number,
    editId: number,
    selectItem: any[],
    selectTreeData: any[],
    page: number,
    pageSize: number,
    total: number,
    search: any
}

export default class PowerManage extends Component<IPorps, IStates> {
    // 表格设置
    private column = [
        {
            key: "name",
            dataIndex: "name",
            title: "权限名称",
            align: "center"
        },
        {
            key: "Id",
            dataIndex: "Id",
            title: "权限Id",
            align: "center"
        },
        {
            key: "parentId",
            dataIndex: "parentId",
            title: "父级Id",
            align: "center"
        },
        {
            key: "code",
            dataIndex: "code",
            title: "权限类型",
            align: "center",
            render: (text: any) => {
                if (text === "1") {
                    return text = <Button type="link">按钮权限</Button>
                } else if (text === "0") {
                    return text = <Button type="link" className="agree">菜单权限</Button>
                }
            }
        },
        {
            key: "auth",
            dataIndex: "auth",
            title: "权限标识",
            align: "center"
        },
        {
            key: "createtime",
            dataIndex: "createtime",
            title: "创建时间",
            align: "center"
        },
        {
            key: "do",
            dataIndex: "do",
            title: "操作",
            align: "center",
            render: (text: any, record: any) => {
                const item = record
                return (
                    <div className="do">
                        <Power authKey="power:power:update">
                            <Button size="small" type="primary" icon={<EditFilled />} onClick={() => { this.openEditDia(item) }} />
                        </Power>
                        <Power authKey="power:power:remove">
                            <Popconfirm title="您确定要删除吗？" okText="是" cancelText="否"
                                onConfirm={this.delete} visible={item.key === this.state.popVisible}
                                onCancel={() => { this.setState({ popVisible: "-1" }) }}>
                                <Button size="small" danger icon={<DeleteFilled />} onClick={() => { this.openPopDia(item) }} />
                            </Popconfirm>
                        </Power>
                    </div>
                )
            }
        }
    ]
    private dialogFormCol = () => {
        return [
            {
                type: 'input',
                label: "权限名称",
                name: "name",
                rules: [
                    { required: true, message: "请输入名称" }
                ],
                component: {
                    placeholder: "请输入名称",
                },
                style: { borderRadius: "5px" }
            },
            {
                type: 'select',
                label: "权限类型",
                name: "code",
                option: [
                    { key: "0", value: "菜单权限" },
                    { key: "1", value: "按钮权限" }
                ],
                rules: [
                    { required: true, message: "请选择权限类型" }
                ],
                component: {
                    placeholder: "请选择权限类型",
                },
                style: { borderRadius: "5px" }
            },
            {
                type: 'cascader',
                label: "父级权限",
                name: "parentId",
                option: this.state.selectTreeData,
                rules: [
                    { required: true, message: "请选择父级菜单" }
                ],
                component: {
                    placeholder: "请选择父级菜单",
                },
                style: { borderRadius: "5px" }
            },
            {
                type: 'input',
                label: "权限标识",
                name: "auth",
                rules: [
                    { required: true, message: "请输入权限标识" }
                ],
                component: {
                    placeholder: "请输入权限标识",
                },
                style: { borderRadius: "5px" }
            },
        ]
    }
    private searchCol = [
        {
            type: 'input',
            name: "name",
            label: "权限名称",
            component: {
                placeholder: "请输入权限名称",
            },
            style: { borderRadius: "5px" }
        }
    ]
    private dialogFormRef = React.createRef<FormInstance>() as any
    constructor(props: IPorps) {
        super(props)
        this.state = {
            powerList: [],
            loading: true,
            popVisible: "-1",
            visible: false,
            title: "",
            delId: 0,
            editId: 0,
            selectTreeData: [],
            selectItem: [],
            total: 0,
            page: 1,
            pageSize: 5,
            search: null
        }
    }
    public componentDidMount() {
        this.fetchData(1, 5)
        this.getPowerAll()
    }
    // 获取数据
    public fetchData = async (page: number, pageSize: number) => {
        const res = await getPowerInfo({ page, pageSize }, this.state.search)
        res.data.data.map((item: any) => {
            return item.key = item.Id
        })
        this.setState({ loading: false, powerList: res.data.data, total: res.data.total })
    }
    // 获取所有一级权限
    public getPowerAll = async () => {
        const selectTreeData: ISelectTreeData[] = []
        selectTreeData.unshift({ label: "食品溯源工作台", value: 0, children: [] })
        const res = await getPowerAll()
        res.data.data.forEach((item: any) => {
            selectTreeData[0].children.push({ label: item.name, value: item.Id })
        })
        this.setState({ selectTreeData: selectTreeData })
    }
    // 页码切换监听事件
    public pageChange = (page: number, pageSize?: number) => {
        if (pageSize) {
            this.setState({ page, pageSize }, () => {
                this.fetchData(page, pageSize)
            })
        }
    }
    public search = (item: any) => {
        if (item.name === undefined || item.name === '') {
            this.setState({ search: null }, () => {
                this.fetchData(this.state.page, this.state.pageSize)
            })
            return
        }
        this.setState({ search: item }, async () => {
            const res = await getPowerInfo({ page: 1, pageSize: 1 }, this.state.search)
            const { status, msg, data,total } = res.data
            if (status === 203) {
                message.error({ content: msg, style: { marginTop: "20%" } })
            } else {
                message.success({ content: msg, style: { marginTop: "20%" } })
                this.setState({ powerList: data,total })
            }
        })

    }
    // 打开对话框
    public openAddDialog = () => {
        this.setState({ visible: true, title: "权限添加" })
    }
    // 打开编辑对话框
    public openEditDia = (item: any) => {
        this.setState({ visible: true, title: "权限编辑", editId: item.Id }, () => {
            if (item.parentId !== 0) {
                item.parentId = [0, item.parentId]
            } else {
                item.parentId = [0]
            }
            this.dialogFormRef.current.setFieldsValue(item)
        })
    }
    public openPopDia = (item: any) => {
        this.setState({ popVisible: item.key, delId: item.Id })
    }
    // 点击对话框确认事件
    public onAddOk = () => {
        this.dialogFormRef.current.validateFields(this.add())
    }
    public onEditOk = () => {
        this.dialogFormRef.current.validateFields(this.edit())
    }
    public add = () => {
        const values = this.dialogFormRef.current.getFieldsValue()
        if (values.parentId !== undefined) {
            values.parentId = values.parentId.pop()
            addPowerInfo(values).then((res: any) => {
                const { msg, status } = res.data
                if (status === 203) {
                    message.error({ content: msg, style: { marginTop: "20%" } })
                } else if (status === 200) {
                    message.success({ content: msg, style: { marginTop: "20%" } })
                    this.cancel()
                }
            })
        }
    }
    public edit = async () => {
        const values = this.dialogFormRef.current.getFieldsValue()
        if (values.parentId !== undefined) {
            values.Id = this.state.editId
            values.parentId = values.parentId.pop()
            const res = await editPowerInfo(values)
            const { status, msg } = res.data
            if (status === 203) {
                message.error({ content: msg, style: { marginTop: "20%" } })
            } else if (status === 200) {
                message.success({ content: msg, style: { marginTop: "20%" } })
                this.cancel()
            }
        }
    }
    public delete = async () => {
        const res = await deletePowerInfo(this.state.delId)
        const { status, msg } = res.data
        if (status === 203) {
            message.error({ content: msg, style: { marginTop: "20%" } })
        } else if (status === 200) {
            message.success({ content: msg, style: { marginTop: "20%" } })
            this.setState({ popVisible: "-1" })
            this.fetchData(this.state.page, this.state.pageSize)
        }
    }
    public cancel = () => {
        this.setState({ visible: false }, () => {
            this.dialogFormRef.current.resetFields()
            this.fetchData(this.state.page, this.state.pageSize)
        })
    }
    public getContent = () => {
        return (
            <DialogForm ref={this.dialogFormRef} column={this.dialogFormCol()} go={() => { }}></DialogForm>
        )
    }
    public renderModal = (item?: string) => {
        return (<Modal
            title={this.state.title}
            visible={this.state.visible}
            content={this.getContent()}
            onOk={item === "" ? this.onAddOk : this.onEditOk}
            onCancel={this.cancel}></Modal>)
    }
    public renderButton() {
        return (
            <div>
                <Power authKey="power:power:save">
                    <Button type="primary" onClick={() => { this.openAddDialog() }}>新增权限</Button>
                </Power>
            </div>
        )
    }
    public render() {
        return (
            <div className="source">
                <Card className="card">
                    <HeaderSearch
                        authKey="power:power:list"
                        column={this.searchCol}
                        search={this.search}></HeaderSearch>
                    {this.renderButton()}
                    <InfoTable
                        columns={this.column}
                        loading={this.state.loading}
                        dataSource={this.state.powerList}
                        tableKey="menuTable"
                        pageChange={this.pageChange}
                        total={this.state.total}>
                    </InfoTable>
                </Card>
                {this.state.title === "权限添加" ? this.renderModal("") : this.renderModal()}
            </div>
        )
    }
}